package bubbleSort;

import emergent.Detector;
import emergent.FeedBack;
import emergent.World;

public class TerminationDetection implements
		Detector<BubbleSortWorld, SortingFeedBack> {

	@Override
	public void applyFeedBack(SortingFeedBack feedback, BubbleSortWorld world) {
		if (feedback.isSorted()) {
			for (int i = 0; i < world.getMaxRows(); i++) {
				for (int j = 0; j < world.getMaxColumns(); j++) {
					world.getAgent(i, j).kill();
				}
			}
		}
	}

	@Override
	public SortingFeedBack detect(BubbleSortWorld world) {

		// Check if they are sorted horizontally
		for (int i = 0; i < world.getMaxRows(); i++) {
			int minimum = 0;
			for (int j = 0; j < world.getMaxColumns(); j++) {
				if (world.getAgent(i, j).getNumberValue() >= minimum) {
					minimum = world.getAgent(i, j).getNumberValue();
				} else {
					System.out.println("not sorted");
					return (new SortingFeedBack(false));
				}
			}
		}

		// Check if they are sorted vertically
		for (int j = 0; j < world.getMaxColumns(); j++) {
			int minimum = 0;
			for (int i = 0; i < world.getMaxRows(); i++) {
				if (world.getAgent(i, j).getNumberValue() >= minimum) {
					minimum = world.getAgent(i, j).getNumberValue();
				} else {
					System.out.println("not sorted");
					return (new SortingFeedBack(false));
				}
			}
		}
		System.out.println("<<Sorted>>");
		System.out.println("Number of swaps " + world.numberOfSwaps);
		return (new SortingFeedBack(true));
		
	}

}
